﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Web.Security;
using TBM.Core;
using System.Data;

namespace TBM.Filters
{
    public class ActionFilters : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            SqlCommand cmd = new SqlCommand();
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;
            string actionResultType = filterContext.Result.GetType().Name;
            bool logEnabled = true;
            int errorCode = 0;

            cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Controller", SqlDbType.VarChar, 30);
            cmd.Parameters.Add("@Action", SqlDbType.VarChar, 30);
            cmd.Parameters.Add("@Type", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@Message", SqlDbType.NVarChar, 100);

            // 执行结果异常
            if (filterContext.Exception != null)
            {
                cmd.CommandText = "insert into dbo.Exception(UID, Controller, Action, Type, Message) values(@UID, @Controller, @Action, @Type, @Message)";
                cmd.Parameters["@Message"].Value = filterContext.Exception.Message;
                errorCode = 500;
            }
            // 正常情况，不记录ActionResult类似的日志
            else if (actionResultType == "JsonResult")
            {
                //Models.ExecuteResult result = (Models.ExecuteResult)((JsonResult)filterContext.Result).Data;
                //cmd.CommandText = "insert into dbo.[Log](UID, Controller, Action, Type, Result, Message) values(@UID, @Controller, @Action, @Type, @Result, @Message)";
                //cmd.Parameters.Add("@Result", SqlDbType.Bit);
                //cmd.Parameters["@Message"].Value = result.Message;
                //cmd.Parameters["@Result"].Value = result.Result;
                logEnabled = false;
            }
            else
            {
                logEnabled = false;
            }

            if (logEnabled)
            {
                string uid = HttpContext.Current.User.Identity.Name;
                if(String.IsNullOrEmpty(uid)){
                    uid = Core.CommandParamType.NullOrString(request["username"]).ToString();
                }
                cmd.Parameters["@UID"].Value = uid;
                cmd.Parameters["@Controller"].Value = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                cmd.Parameters["@Action"].Value = filterContext.ActionDescriptor.ActionName;
                cmd.Parameters["@Type"].Value = actionResultType;
                using (cmd.Connection = new SqlConnection(Config.ConnectionString))
                {
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
            }

            if (errorCode == 500)
            {
                bool ajaxRequest = false;
                if (request["ajax"] != null)
                {
                    bool.TryParse(request["ajax"].ToString(), out ajaxRequest);
                }

                if (ajaxRequest)
                {
                    bool redirect = false;
                    if (request["redirect"] != null)
                    {
                        bool.TryParse(request["redirect"].ToString(), out redirect);
                    }

                    if (!redirect)
                    {
                        response.Clear();
                        response.ContentType = "application/json";
                        response.Write("{" +
                            String.Format("\"Result\": false, \"Status\": {0}, \"Message\": \"{1}\"",
                                500,
                                "程序执行错误"
                            ) + "}");
                        response.End();
                    }
                    else
                    {
                        response.Redirect("~/error/c500");
                    }
                }
                else
                {
                    response.Redirect("~/error/code500");
                }
            }
        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 加载用户信息
            if (HttpRuntime.Cache.Get("User") == null)
            {
                string UID = HttpContext.Current.User.Identity.Name;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = new SqlConnection(Config.ConnectionString);
                cmd.Connection.Open();
                cmd.CommandText = "select [UID], FirstName, LastName, Email, Phone, QQ, Memo from dbo.Users where [UID] = @UID";
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@UID", SqlDbType.VarChar, 15);
                cmd.Parameters["@UID"].Value = UID;

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        TBM.Models.User user = new Models.User
                        {
                            UID = dr["UID"].ToString(),
                            FirstName = dr["FirstName"].ToString(),
                            LastName = dr["LastName"].ToString(),
                            Email = dr["Email"].ToString(),
                            Phone = dr["Phone"].ToString(),
                            QQ = dr["QQ"].ToString(),
                            Memo = dr["Memo"].ToString()
                        };

                        HttpRuntime.Cache.Insert("User", user);
                    }
                }

                if (cmd.Connection.State != ConnectionState.Closed)
                {
                    cmd.Connection.Close();
                }
            }
        }
    }
}